import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getarchives } from "@/services/modules/archives"
import { getlabel, readingList } from '@/services';
import { labelItem, listItem } from '@/utils/Article';
export interface IndexModelState {
    name: string,
    list: any,
    keys: [],
    readList:Array<listItem>,
    labellist:Array<labelItem>
}

export interface IndexModelType {
    namespace: 'archives';
    state: IndexModelState;
    effects: {
        query: Effect;
        readinglist:Effect;
        getlabel:Effect
    };
    reducers: {
        save: Reducer<IndexModelState>;
        // 启用 immer 之后
        // save: ImmerReducer<IndexModelState>;
    };
    subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
    namespace: 'archives',

    state: {
        name: '',
        list: [],
        keys: [],
        readList:[],
        labellist:[]
    },

    effects: {
        *query({ payload }, { call, put }) {
            let res = yield call(getarchives)
            var keys = [];      
            for (var key in res.data) {
                keys.unshift(key);    
            }       
            yield put({
                type: "save",
                payload: {
                    list: res.data,
                    keys,
                }
            })

        },
        *readinglist({payload},{call,put}){
            let result=yield call(readingList)
            yield put({
              type:'save',
              payload:{
                readList:result.data
              }
            })
          },
          *getlabel({payload},{call,put}){
            let result=yield call(getlabel)
            yield put({
              type:'save',
              payload:{
                labellist:result.data
              }
            })
          },
    },
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
        // 启用 immer 之后
        // save(state, action) {
        //   state.name = action.payload;
        // },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathname === '/') {
                    dispatch({
                        type: 'query',
                    });
                }
            });
        },
    },
};

export default IndexModel;